package cn.stylefeng.guns.core.util;

import com.alibaba.fastjson.JSONObject;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import org.apache.catalina.startup.UserConfig;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.UUID;

/**
 * @Author: Xiazt
 * @Date: 2019-09-03 11:57
 */
public class TencentCloudUtils {


    private final static Logger logger = LoggerFactory.getLogger(TencentCloudUtils.class);

    //腾讯云的SecretId
    private static String secretId;
    //腾讯云的SecretKey
    private static String secretKey;
    //腾讯云的bucket (存储桶)
    private static String bucket;
    //腾讯云的region(bucket所在地区)
    private static String region;
    //腾讯云的allowPrefix(允许上传的路径)
    private static String allowPrefix;
    //腾讯云的临时密钥时长(单位秒)
    private static String durationSeconds;
    //腾讯云的访问基础链接:
    private static String baseUrl;

    //读取配置文件，初始化配置
    static {
        ResourceBundle bundle = ResourceBundle.getBundle("tencent");
        secretId = bundle.getString("tencent.SecretId");
        secretKey = bundle.getString("tencent.SecretKey");
        bucket = bundle.getString("tencent.bucket");
        region = bundle.getString("tencent.region");
        allowPrefix = bundle.getString("tencent.allowPrefix");
        durationSeconds = bundle.getString("tencent.durationSeconds");
        baseUrl = bundle.getString("tencent.baseUrl");
    }

    public static COSClient getCosClient() {
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        Region region = new Region("ap-chengdu");
        ClientConfig clientConfig = new ClientConfig(region);
        COSClient cosclient = new COSClient(cred, clientConfig);
        return cosclient;
    }

    /**
     * 上传文件，本地
     *
     * @param path 文件服务器下的根路径,即key,如: doc/picture.jpg
     * @param file
     * @return 成功返回文件路径, 失败返回null
     */
    public static String uploadFile(String path, File file ) {
        COSClient cosclient = getCosClient();
        return putObject ( path,  file, cosclient,bucket);
    }


    private static String putObject(String path, File file, COSClient cosclient, String bucket){
        // 上传 object, 建议 20M 以下的文件使用该接口
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, path, file);
        String rtValue = null;
        try {
            PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
            // 成功：putobjectResult 会返回文件的 etag
            String etag = putObjectResult.getETag();
            rtValue = baseUrl + path;
        } catch (CosServiceException e) {
            //失败，抛出 CosServiceException
            e.printStackTrace();
        } catch (CosClientException e) {
            //失败，抛出 CosClientException
            e.printStackTrace();
        } finally {
            // 关闭客户端
            cosclient.shutdown();
            //返回文件的网络访问url
            return rtValue;
        }
    }

    /**
     * 使用流上传
     *
     * @param file
     * @param prefix
     * @return
     */
    public static Map<String, String> uploadFile(MultipartFile file, String prefix) {
        COSClient cosclient = getCosClient();
        return putObject ( file,  prefix, cosclient,bucket);
    }

    private static  Map<String,String> putObject (MultipartFile file, String prefix, COSClient cosclient, String bucket){
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(file.getSize());
        objectMetadata.setContentType(file.getContentType());

        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String newFileName = prefix + UUID.randomUUID().toString() + suffix;

        // 上传 object, 建议 20M 以下的文件使用该接口
        PutObjectRequest putObjectRequest = null;
        try {
            putObjectRequest = new PutObjectRequest(bucket, newFileName, file.getInputStream(), objectMetadata);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String rtValue = null;
        HashMap<String, String> map = new HashMap<>();
        try {
            PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
            // 成功：putobjectResult 会返回文件的 etag
            String etag = putObjectResult.getETag();
            rtValue = baseUrl + newFileName;
            map.put("fileName", newFileName);
            map.put("filePath", rtValue);
        } catch (CosServiceException e) {
            //失败，抛出 CosServiceException
            e.printStackTrace();
        } catch (CosClientException e) {
            //失败，抛出 CosClientException
            e.printStackTrace();
        } finally {
            // 关闭客户端
            cosclient.shutdown();
            //返回文件的网络访问url
            return map;
        }
    }
    /**
     * 使用流上传文件，覆盖原文件
     *
     * @param file
     * @param fileName
     * @param isOverride
     * @return
     */
    public static Map<String, String> uploadFile(MultipartFile file, String fileName, Boolean isOverride) {
        COSClient cosclient = getCosClient();
        return putObject1 ( file,  fileName, cosclient,bucket);
    }

    private static Map<String,String> putObject1 (MultipartFile file, String fileName , COSClient cosclient, String bucket){

        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(file.getSize());
        objectMetadata.setContentType(file.getContentType());

        // 上传 object, 建议 20M 以下的文件使用该接口
        PutObjectRequest putObjectRequest = null;
        try {
            putObjectRequest = new PutObjectRequest(bucket, fileName, file.getInputStream(), objectMetadata);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String rtValue = null;
        HashMap<String, String> map = new HashMap<>();
        try {
            PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
            // 成功：putobjectResult 会返回文件的 etag
            String etag = putObjectResult.getETag();
            rtValue = baseUrl + fileName;
            map.put("fileName", fileName);
            map.put("filePath", rtValue);
        } catch (CosServiceException e) {
            //失败，抛出 CosServiceException
            e.printStackTrace();
        } catch (CosClientException e) {
            //失败，抛出 CosClientException
            e.printStackTrace();
        } finally {
            // 关闭客户端
            cosclient.shutdown();
            //返回文件的网络访问url
            return map;
        }
    }
    public static void deleteObject(String key) {
        COSClient cosClient = getCosClient();
        // 删除文件
        cosClient.deleteObject(bucket, key);
    }

    /**
     * 复制对象
     *
     * @param sourceKey
     * @param destinationKey
     */
    public static void copyObject(String sourceKey, String destinationKey) {
        if(!destinationKey.equals(sourceKey)){
            COSClient cosClient = getCosClient();
            CopyObjectRequest copyObjectRequest = new CopyObjectRequest(bucket, sourceKey, bucket, destinationKey);
            cosClient.copyObject(copyObjectRequest);
        }
    }

    /**
     * 图片鉴黄
     *
     * @param multipartFile
     * @return
     */
    public static Boolean checkPic(MultipartFile multipartFile) {
        try {

            CloseableHttpClient httpclient = HttpClients.createDefault();

            CloseableHttpResponse response = null;

            // 获取accessToken
            String accessToken = getSuccessToken();

            HttpPost request = new HttpPost("https://api.weixin.qq.com/wxa/img_sec_check?access_token=" + accessToken);
            request.addHeader("Content-Type", "application/octet-stream");


            InputStream inputStream = multipartFile.getInputStream();

            byte[] byt = new byte[inputStream.available()];
            inputStream.read(byt);
            request.setEntity(new ByteArrayEntity(byt, ContentType.create("image/jpg")));


            response = httpclient.execute(request);
            HttpEntity httpEntity = response.getEntity();
            String result = EntityUtils.toString(httpEntity, "UTF-8");// 转成string
            JSONObject jso = JSONObject.parseObject(result);
            logger.info(jso + "-------------验证效果");


            Object errcode = jso.get("errcode");
            int errCode = (int) errcode;
            if (errCode == 0) {
                return true;
            } else if (errCode == 87014) {
                logger.info("图片内容违规-----------");
                return false;
            }

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("----------------调用腾讯内容过滤系统出错------------------");
            return true;
        }
    }

    /**
     * 文字鉴黄
     *
     * @param textConetnt
     * @return
     */
    public static Boolean checkText(String textConetnt) {

        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();

            CloseableHttpResponse response = null;

            String accessToken = getSuccessToken();
            HttpPost request = new HttpPost("https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" + accessToken);
            request.addHeader("Content-Type", "application/json;charset=UTF-8");

            Map<String, String> paramMap = new HashMap<String, String>();
            paramMap.put("content", textConetnt);
            request.setEntity(new StringEntity(JSONObject.toJSONString(paramMap), ContentType.create("application/json", "utf-8")));


            response = httpclient.execute(request);
            HttpEntity httpEntity = response.getEntity();
            String result = EntityUtils.toString(httpEntity, "UTF-8");// 转成string
            JSONObject jso = JSONObject.parseObject(result);


            Object errcode = jso.get("errcode");
            int errCode = (int) errcode;
            if (errCode == 0) {
                return true;
            } else if (errCode == 87014) {
                logger.info("内容违规-----------" + textConetnt);
                return false;
            }

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("----------------调用腾讯内容过滤系统出错------------------");
            return true;
        }
    }

    /**
     * 获取小程序successToken
     *
     * @return
     */
    public static String getSuccessToken() {
        // 获取accessToken
        HashMap<String, String> map = new HashMap<>();
        String urlWithParam = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx34a9627a86b963be&sec&secret=0f8f13ace7e8926059f5f3e270766373";
        String s = HttpClientUtil.doPost(urlWithParam, map, "");
        JSONObject jsonObject = JSONObject.parseObject(s);
        String accessToken = (String) jsonObject.get("access_token");
        return accessToken;
    }

    /**
     * 判断存储对象图片格式是否是webp
     * @param key
     * @return
     */
    public static Boolean  isType_Webp (String key){
        COSClient cosClient = getCosClient();
        ObjectMetadata objectMetadata = cosClient.getObjectMetadata("baize-1257801634", key);
        Map<String, Object> rawMetadata = objectMetadata.getRawMetadata();
        String content_type = rawMetadata.get("Content-Type").toString();
        System.out.println(content_type);
        return content_type.equals("image/webp")?true:false;
    }

    /**
     * 下载到本地
     * @param key
     */
    public static void getObject (String key){
        COSClient cosClient = getCosClient();
        File downFile = new File("D:/file/img/"+key);
        GetObjectRequest getObjectRequest = new GetObjectRequest("baize-1257801634", key);
        ObjectMetadata downObjectMeta = cosClient.getObject(getObjectRequest, downFile);
    }


}
